<?php

namespace App\Console\Commands\Mybank;

use App\Library\Rms\RmsUserApi;
use App\Models\Common\ConfigModel;
use App\Models\Kms\User\KmsUser;
use App\Service\Common\SmsService;
use App\Service\System\SystemNotifyService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class OpenPayNotify extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mybank:open-pay-notify {userId=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开通网商银行通知';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws GuzzleException
     */
    public function handle()
    {
        $userId = $this->argument('userId');

        $roleJson = (string)ConfigModel::query()
            ->where('module', 'rmsMerchantUser')
            ->where('name', 'merchantUserRole')
            ->value('value');

        $notifyId = (int)ConfigModel::query()
            ->where('module', 'mybank')
            ->where('name', 'openPayNotifyId')
            ->value('value');

        if (!mb_strlen($roleJson) || !$notifyId) {
            return;
        }

        $roleArr = array_values(json_decode($roleJson, true));

        $userList = (new RmsUserApi())->getUserListByPower(implode(',', $roleArr))['data'] ?? [];
        //方便测试
        if ($userId != 0) {
            $userIds = collect($userList)->pluck('userId')->values()->toArray();
            if (in_array($userId, $userIds)) {
                $userList = [
                    [
                        'userId' => $userId,
                        'mobile' => KmsUser::query()->where('rmsUserId', $userId)->value('mobile'),
                    ]
                ];
            } else {
                return;
            }
        }

        try {
            collect($userList)->chunk(30)->each(function ($lists) use ($notifyId){
                //存储已经推送的
                $cacheKey   = 'myBank:openBankPayNotify:' . Carbon::now()->format('Y-m-d');
                $sent       = Cache::get($cacheKey) ?: [];
                $sentUserId = collect($sent)->pluck('userId')->unique()->values()->toArray();
                $userIds    = $lists->pluck('userId')->unique()->values()->toArray();
                //要执行的提醒
                $willSendUserId = array_diff($userIds, $sentUserId);
                Log::info('发送开通网商支付提醒' . json_encode($willSendUserId));
                //发送推送
                SystemNotifyService::preSend($notifyId, $willSendUserId);
                foreach ($lists as $list) {
                    //过滤掉已经发送过的
                    if (!in_array($list['userId'], $willSendUserId)) {
                        continue;
                    }
                    //发送短信
                    $sms = new SmsService();
                    $sms->aliyunSend($list['mobile'], config('sms.template.mybankOpenPayNotify'), []);
                }
                $send = array_merge($sent, $lists->toArray());
                Cache::put($cacheKey, $send, 86400);
            });
        } catch (\Exception $exception) {
            return;
        }
    }
}
